package com.example.canalclientsync.canal.handler;

import com.example.canalclientsync.canal.po.VirtualModel;
import com.example.canalclientsync.canal.service.ModelService;
import com.example.canalclientsync.es.document.EsModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 模型创建、改名、删除、修改所有者
 *
 * @author chen.cr
 * @since 2023/9/14
 */
@Component
@Slf4j
public class VirtualModelHandler implements EntryHandler<VirtualModel> {

    @Resource
    private ElasticsearchRestTemplate elasticsearchTemplate;
    @Resource
    private ModelService modelService;

    @Override
    public void insert(VirtualModel model) {
        log.info("[INSERT] >>>>>>>>>> virtualModel, modelId:{}", model.getModelId());

        EsModel esModel = modelService.buildFromVirtualModel(model);
        if (esModel == null) {
            log.info("构造数据异常，同步Insert失败，modelId:{}", model.getModelId());
            return;
        }

        elasticsearchTemplate.save(esModel);
        log.info("<<<<<< EsModel保存模型成功, modelId:{}", model.getModelId());
    }

    @Override
    public void update(VirtualModel before, VirtualModel after) {
        log.info("[UPDATE] >>>>>>>>>> virtualModel, modelId:{}", after.getModelId());

        // mysql逻辑删除，es里直接删除
        if (after.getVisible() == 1) {
            elasticsearchTemplate.delete(after.getModelId().toString(), EsModel.class);
            log.info("<<<<<< ES删除模型成功(visible=1), modelId:{}", after.getModelId());
            return;
        }

        EsModel esModel = modelService.buildFromVirtualModel(after);
        if (esModel == null) {
            log.info("<<<<<< 构造数据异常，同步Update失败，modelId:{}", after.getModelId());
            return;
        }

//        elasticsearchTemplate.delete(after.getModelId().toString(), EsModel.class);
        elasticsearchTemplate.save(esModel);
        log.info("<<<<<< ES更新模型成功, modelId:{}", after.getModelId());
    }


    @Override
    public void delete(VirtualModel model) {
        log.info("[DELETE] >>>>>>>>>> virtualModel, modelId:{}", model.getModelId());
        elasticsearchTemplate.delete(model.getModelId().toString(), EsModel.class);
        log.info("<<<<<< ES删除模型成功, modelId:{}", model.getModelId());
    }



}
